const { app, BrowserWindow, Menu, dialog, ipcMain } = require('electron')
const fs = require('fs')

/**
 * Grab the file path and open it
 * @param {array} filePaths the file path from the fileObj
 * @return {promise} return a promise 
 */
function readFile(filePaths) {
    return new Promise((resolver, rejecter) => {
        // we don't care about the rest of the selected file only the first one for now
        fs.readFile(filePaths[0], {encoding: 'utf8'}, function(err, data) {
            if (err) {
                return rejecter(err)
            }
            resolver(data)
        })
    })
}


app.whenReady().then(function() {
    const mainWindow = new BrowserWindow({
        backgroundColor: '#FFF',
        webPreferences: {
            devTools: true,
            nodeIntegration: true
        },
        show: false,
    })
    
    const menu = Menu.buildFromTemplate([
        {
            label: 'Menu',
            submenu: [
                {
                    label:'Open File',
                    accelerator: 'CmdOrCtrl+O',
                    click() {
                        dialog.showOpenDialog({
                        properties: ['openFile'],
                        filters: [
                            { name: 'Markdown', extensions: ['md'] }
                        ]
                    })
                    .then(function(fileObj) {
                        console.log('got file?', fileObj)
                        if (!fileObj.canceled) {
                            readFile(fileObj.filePaths)
                                .then(md => {
                                    mainWindow.webContents.send('FILE_OPEN', md)
                                })
                        }
                    })
                    .catch(function(err) {
                        console.error(err)  
                    })
                } 
            },
            {
                label:'Exit',
                accelerator: 'CmdOrCtrl+x',
                click() {
                    app.quit()
                } 
              }
            ]
        }
    ])
    Menu.setApplicationMenu(menu)
    
    // mainWindow.maximize();
    mainWindow.loadURL(`file://${__dirname}/index.html`)
    mainWindow.show();
    
})
